package com.songcan.oauth.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songcan.model.oauth.SysDept;
import com.songcan.model.oauth.SysOrganizational;
import com.songcan.oauth.mapper.SysOrganizationalMapper;
import com.songcan.oauth.service.SysOrganizationalService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.Objects;

@Service
public class SysOrganizationalServiceImpl extends ServiceImpl<SysOrganizationalMapper, SysOrganizational> implements SysOrganizationalService {


    @Override
    public void addOrganizational(String name, Integer sort, Long parentId, String remark) {
        DecimalFormat decimalFormat = new DecimalFormat("0000");
        String levelCode = "";
        SysOrganizational sysOrganizational = null;
        if(Objects.nonNull(parentId)){
            int childCount = count(Wrappers.lambdaQuery(new SysOrganizational())
                    .eq(SysOrganizational::getParentId,parentId).eq(SysOrganizational::getDelFlag,0));
            SysOrganizational  area = getById(parentId);
            if(childCount > 0){
                levelCode = area.getLevelCode() +"-"+ decimalFormat.format(childCount);

            }else{
                levelCode = area.getLevelCode()+"-"+"0001";
            }
        }else{
            sysOrganizational = getOne(Wrappers.lambdaQuery(new SysOrganizational()).isNull(SysOrganizational::getParentId).orderByDesc(SysOrganizational::getCreateTime).last(" limit 1"));
            if(Objects.isNull(sysOrganizational)){
                levelCode = "0000";
            }else {
                levelCode = sysOrganizational.getLevelCode();
            }
        }
        String[] level = levelCode.split("-");
        while (count(Wrappers.lambdaQuery(new SysOrganizational()).eq(SysOrganizational::getLevelCode,levelCode))>0){

            Long code = Long.valueOf(level[level.length-1]);
            code++;
            level[level.length-1] = String.valueOf(decimalFormat.format(code));
            levelCode = StringUtils.join(level,"-");
        }
        sysOrganizational = new SysOrganizational(IdWorker.getId(),name,levelCode,parentId,remark,0,new Date());
                //new SysOrganizational(IdWorker.getId(),name,levelCode,new Date(),null,0,parentId,remark);
        save(sysOrganizational);
    }
}
